package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseMapper;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.entity.Permission;
import com.atguigu.entity.Role;
import com.atguigu.entity.RolePermission;
import com.atguigu.mapper.AdminMapper;
import com.atguigu.mapper.PermissionMapper;
import com.atguigu.mapper.RoleMapper;
import com.atguigu.mapper.RolePermissionMapper;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: 翟文海
 * @Date: 2022/10/25/025 12:36
 * @Version: 1.0
 * @Description:
 **/
@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    protected BaseMapper<Role> getMapper() {
        return roleMapper;
    }

    @Override
    public void insert(Role role) {
        Role dbRole = roleMapper.getByRoleName(role.getRoleName());
        if (dbRole != null) {
            throw new RuntimeException("角色名已经存在，不能重复添加");
        }
        roleMapper.insert(role);
    }

    @Override
    public void update(Role role) {
        Role dbRole = roleMapper.getByRoleName(role.getRoleName());
        if (dbRole != null) {
            throw new RuntimeException("此角色已经存在，不能重复");
        }
        roleMapper.update(role);
    }

    @Override
    public List<Map<String, Object>> findPermissionByRoleId(Long id) {
        //查询所有权限列表
        List<Permission> permissionList = permissionMapper.findAll();
        //根据角色id查询该角色的权限id
        List<Long> permissionIdList = rolePermissionMapper.findPermissionIdListByRoleId(id);
        //查询所有父节点id
        List<Long> permissionPrentId = permissionMapper.findPermissionByParentId();
        List<Map<String, Object>> mapList = permissionList.stream()
                .map(permission -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", permission.getId());
                    map.put("pId", permission.getParentId());
                    map.put("name", permission.getName());
                    //map.put("open", permissionMapper.findPermissionCountByParentId(permission.getId()) > 0);
                    map.put("checked", permissionIdList.contains(permission.getId()));
                    map.put("open", permissionPrentId.contains(permission.getId()));
                    return map;
                }).collect(Collectors.toList());
        return mapList;
    }

    @Override
    public List<Role> findByAdminId(Long adminId) {
        return roleMapper.findByAdminId();
    }

    /**
     * @param roleId        角色id
     * @param permissionIds 勾选的权限id
     */
    @Transactional
    @Override
    public void saveRolePermission(Long roleId, List<Long> permissionIds) {

        //目标：保存角色勾选的权限
        //删除权限
        List<Long> removePermissionIdList = null;
        //1.先将以前用户管理的权限找到
        List<Long> permissionIdListByRoleId = rolePermissionMapper.findPermissionIdListByRoleId(roleId);
        if (!CollectionUtils.isEmpty(permissionIds)) {
            removePermissionIdList = permissionIdListByRoleId.stream()
                    .filter(permissionId -> !permissionIds.contains(permissionId))
                    .collect(Collectors.toList());
        } else {
            //如果用户一个都没勾选，说明以前的都得删除
            removePermissionIdList = permissionIdListByRoleId;
        }
        if (removePermissionIdList.size()>0&&removePermissionIdList!=null) {
            rolePermissionMapper.deleteBatch(roleId,removePermissionIdList);
        }

        //添加权限

        //2.将之前存在但是被删除的权限改为没有被删除
        if (!CollectionUtils.isEmpty(permissionIds)) {
            permissionIds.stream()
                    .forEach(permissionId -> {
                        //1.查找之前已经存在过的关联权限
                        RolePermission rolePermissionDel = rolePermissionMapper.findPermissionDelByRoleIdAndPid(roleId,permissionId);
                        //之前存在，并且还要继续存在的
                        if (rolePermissionDel!=null){
                            if (rolePermissionDel.getIsDeleted() == 1) {
                                //之前关联过但是已经被删除的，修改为没有被删除
                                rolePermissionDel.setIsDeleted(0);
                                rolePermissionMapper.update(rolePermissionDel);
                            }
                        } else {
                            rolePermissionMapper.insertBatch(roleId, permissionIds);
                        }
                    });
        }
    }
}
